import json
import os
import re
import shutil

import yaml

import pandas as pd

repo_path = "/home/openEuler15/code/"
code_path = "/home/openEuler15/PycharmProjects/tools"


def collect_package_info():
    file_path = repo_path + "/community/repository/src-openeuler.yaml"
    if not os.path.exists(file_path):
        os.chdir(repo_path)
        cmd = "git clone https://gitee.com/openeuler/community.git"
        if os.system(cmd) != 0:
            print("Git clone community failed!")
    with open(file_path) as f:
        data = yaml.load(f)
        with open('repos.json', 'w') as f1:
            json.dump(data, f1)
            # print(data)


def get_package_info(name):
    os.chdir(code_path)
    if not os.path.exists('repos.json'):
        collect_package_info()
    with open('repos.json') as f:
        data = json.load(f)
        repositories = data.get('repositories')
        for repo in repositories:
            # print(repo)
            if repo.get('name') == name:
                description = repo.get('description')
                upstream = repo.get('upstream')
                return description, upstream


# openEuler-20.03-LTS
# openEuler-20.03-SP1
# openEuler-20.03-SP2
# openEuler-20.09
# openEuler-21.03
def check_git_branch_exists(branches):
    brans = ["openEuler-20.03-LTS", "openEuler-20.03-LTS-SP1", "openEuler-20.03-LTS-SP2", "openEuler-20.09", "openEuler-21.03"]
    res = [False, False, False, False, False]
    for index, br in enumerate(brans):
        for branch in branches:
            if br == branch.get('name'):
                res[index] = True
    return res


def _get_obs_package(brans):
    res = []
    for index, br in enumerate(brans):
        cmd = "osc list {}".format(br)
        p = os.popen(cmd)
        data = p.read().strip().split('\n')
        res.append(data)
    return res


def get_package_of_branch():
    brans = ["openEuler:20.03:LTS", "openEuler:20.03:LTS:SP1", "openEuler:20.03:LTS:SP2", "openEuler:20.09", "openEuler:21.03"]
    brans_epol = ["openEuler:20.03:LTS:Epol", "openEuler:20.03:LTS:SP1:Epol", "openEuler:20.03:LTS:SP2:Epol", "openEuler:20.09:Epol", "openEuler:21.03:Epol"]
    pkgs = _get_obs_package(brans)
    pkgs_epol = _get_obs_package(brans_epol)
    print(pkgs)
    print(pkgs_epol)
    data = []
    for i, v in enumerate(pkgs):
        data.append(v + pkgs_epol[i])
    return data


def check_obs_branch_exists(package_name, pkgs):
    res = [False, False, False, False, False]
    for index, pk in enumerate(pkgs):
        if package_name in pk:
            res[index] = True
    print(res)
    return res


def get_pkg_owner_email(branch, pkg):
    """
    get the email address of the package owner
    """
    _tmpdir = os.popen("mktemp -d").read().strip('\n')
    print(_tmpdir)
    pkg_path = os.path.join(_tmpdir, branch, pkg)
    cmd = "cd %s && osc co %s %s &>/dev/null && cd %s && osc up -S &>/dev/null" % (
            _tmpdir, branch, pkg, pkg_path)
    to_addr = ''
    if os.system(cmd) == 0:
        cmd = "cd {0} && grep -A 1 \"%changelog\" *.spec | grep \"@\" && cd -".format(
                pkg_path)
        email = os.popen(cmd).read()

        if email:
            to_addr = ''.join(re.findall(r"<(.+?)>", email))
    else:
        print("error")
    # shutil.rmtree(_tmpdir)
    return to_addr

def save_excel():
    os.chdir(code_path)
    if not os.path.exists('repos.json'):
        collect_package_info()
    with open('repos.json') as f:
        data = json.load(f)
        repositories = data.get('repositories')
        res = []
        pkgs = get_package_of_branch()
        # get obs owners
        _get_obs_owners()
        with open('test_rjb.txt') as f:
            dst_pkgs = f.read().strip().split('\n')
        for dst_pk in dst_pkgs:
            for repo in repositories:
                name = repo.get('name')
                if name != dst_pk:
                    continue
                dct = {}
                description = repo.get('description')
                upstream = repo.get('upstream')
                sig_name = get_sig_info(name)
                owners = get_pkg_owners(sig_name)
                branches = repo.get('branches')
                gitee_exists = check_git_branch_exists(branches)
                print(gitee_exists)
                obs_exists = check_obs_branch_exists(name, pkgs)
                exists = list(zip(gitee_exists, obs_exists))
                dct["name"] = name
                dct["description"] = description
                dct["upstream"] = upstream
                dct["sig_name"] = sig_name
                dct["maintainer"] = owners
                dct["20.03 LTS"] = exists[0]
                dct["20.03 LTS SP1"] = exists[1]
                dct["20.03 LTS SP2"] = exists[2]
                dct["20.09"] = exists[3]
                dct["21.03"] = exists[4]
                status = [bool(a and b) for a, b in exists]
                email = ''
                if True in status:
                    # email = get_pkg_owner_email(brans[status.index(True)], name)
                    email = get_pkg_owner_email_by_name(status.index(True), name)
                dct["email"] = email
                res.append(dct)
        df = pd.DataFrame(res)
        df.to_excel('result_dst.xlsx')


def collect_sig_info():
    # os.chdir(repo_path)
    file_path = repo_path + "/community/sig/sigs.yaml"
    with open(file_path) as f:
        data = yaml.load(f)
        with open('sigs.json', 'w') as f1:
            json.dump(data, f1)


def get_sig_info(name):
    os.chdir(code_path)
    if os.path.exists('sigs.json'):
        collect_sig_info()
    with open('sigs.json') as f:
        data = json.load(f)
        sigs = data.get('sigs')
        for sig in sigs:
            repositories = sig.get('repositories')
            repo1 = "src-openeuler/{}".format(name)
            repo2 = "openeuler/{}".format(name)
            if repo1 in repositories or repo2 in repositories:
                return sig.get("name")


def get_pkg_owners(sig_name):
    owner_file = repo_path + "community/sig/{}/OWNERS".format(sig_name)
    with open(owner_file) as f:
        data = f.read().strip().split('\n')
        owners = [i.replace('-', '').strip() for i in data[1:]]
        return owners


pkg_owners = []


def _get_obs_owners():
    brans = ["openEuler:20.03:LTS", "openEuler:20.03:LTS:SP1", "openEuler:20.03:LTS:SP2", "openEuler:20.09",
             "openEuler:21.03"]
    for br in brans:
        with open(br + '.json') as f:
            euler = json.load(f)
            pkg_owners.append(euler)


def get_pkg_owner_email_by_name(index, name):
    return pkg_owners[index].get(name)


if __name__ == '__main__':
    save_excel()
